from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class AreasView(View):

    def get(self, request):
        # 1查寻所有省份

        province_list = cache.get('provinces')
        if province_list is None:
            # print("查询省数据")
            try:
                provinces = Area.objects.filter(parent=None)

                # 2 转换为字典
                # {code:0,erromsg:'ok',"province_list":[{"id":id,"name":xxx},{"id":id,"name":xxx},{"id":id,"name":xxx}]}
                province_list = []
                for province in provinces:
                    province_list.append({"id": province.id, "name": province.name})

                cache.set("provinces", province_list, 3600 * 24)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})

        # else:
        #     print("使用查询的省数据")
        # 3 返回响应
        return JsonResponse({"code": 0, "errmsg": "ok", "province_list": province_list})


class SubAreaView(View):

    def get(self, request, id):
        sub_data = cache.get('sub_areas%s' % id)
        if sub_data is None:
            print("获取sub_data")
            try:
                # 1获取id 2根据id查询省或者市的对象
                parent_obj = Area.objects.get(id=id)
                # 3获取省或者市下一级的所有数据
                sub_objs = parent_obj.subs.all()
                # 4 转为字典
                subs = []
                for sub in sub_objs:
                    subs.append({"id": sub.id, "name": sub.name})

                sub_data = {"id": id, "name": parent_obj.name, "subs": subs}

                cache.set('sub_areas%s' % id, sub_data, 3600 * 24)
            except Exception as e:
                print(e)
                return JsonResponse({"code": 400, "errmsg": "查询失败"})
        else:
            print("缓存sub_data")

        # 5 返回数据
        return JsonResponse({"code": 0, "errmsg": "ok", "sub_data": sub_data})
